package com.example.pkmedical.Base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.pkmedical.APP.AppManager;
import com.example.pkmedical.Activity.LockScreenActivity;
import com.example.pkmedical.Base.BaseView;
import com.example.pkmedical.Event.MessageWrap;
import com.example.pkmedical.R;
import com.example.pkmedical.Utils.CommonUtil;
import com.example.pkmedical.Utils.CountTimer;
import com.example.pkmedical.Utils.EventBusUtils;
import com.example.pkmedical.receivers.TimeChangeReceiver;
import com.lzy.imagepicker.view.SystemBarTintManager;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import me.yokeyword.fragmentation.SupportActivity;

import static android.view.View.GONE;

public abstract class BaseActivity extends SupportActivity implements BaseView {
    //当被观察者被订阅会出现Disposable，用于存储Disposable当页面销毁的时候取消订阅
    //  private SweetAlertDialog dialog;
    private View rl_top;
    private View back;
    //    private CountDownTimer countTimerView;
    private TextClock main_date;
    private CountTimer countTimerView;
    private IntentFilter intentFilter;

    private TimeChangeReceiver timeChangeReceiver;
    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSystemBarTint();
        // 添加Activity管理
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            AppManager.getInstance().addActivity(this);
        }
        //注册事件接收
        if (isRegisteredEventBus()) {
            EventBusUtils.register(this);
        }
        intentFilter = new IntentFilter();

        intentFilter.addAction(Intent.ACTION_TIME_TICK);//每分钟变化

        intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);//设置了系统时区

        intentFilter.addAction(Intent.ACTION_TIME_CHANGED);//设置了系统时间

        timeChangeReceiver = new TimeChangeReceiver();

        registerReceiver(timeChangeReceiver, intentFilter);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        main_date = findViewById(R.id.main_date);
        main_date.setFormat24Hour("yyyy-MM-dd HH:mm  EEEE");
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        try {
            rl_top = findViewById(R.id.rl_top);
            if (rl_top != null) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                    rl_top.setVisibility(GONE);
                } else {
                    rl_top.getLayoutParams().height = CommonUtil.getStatusBarHeight(this);
                }
            }
        } catch (Exception e) {

        }
        try {
            back = findViewById(R.id.back);
            if (back != null) {
                back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closeKeyboard();
                        finish();
                    }
                });
            }

        } catch (Exception e) {

        }
        ButterKnife.bind(this);
        initView();
        initData();
        initPresenter();
        countTimerView = new CountTimer(3600000, 1000, this);
//        countTimerView = new CountDownTimer(600000, 1000) {
//
//            @Override
//            public void onTick(long millisUntilFinished) {
//
//            }
//
//            @Override
//            public void onFinish() {
//                BaseActivity.this.startActivity(new Intent(BaseActivity.this, LockScreenActivity.class));
////                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
//            }
//        };
    }

    private void timeStart() {
        new Handler(getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                countTimerView.start();
            }
        });
    }

    /**
     * 接收到分发的事件
     *
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(MessageWrap event) {
    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onReceiveStickyEvent(MessageWrap event) {
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            //获取触摸动作，如果ACTION_UP，计时开始。
            case MotionEvent.ACTION_UP:
                countTimerView.start();
                break;
            //否则其他动作计时取消
            default:
                countTimerView.cancel();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (countTimerView != null) {
            countTimerView.cancel();
        }
        timeStart();
    }

    /**
     * 是否注册事件分发
     *
     * @return true 注册；false 不注册，默认不注册
     */
    protected boolean isRegisteredEventBus() {
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        countTimerView.cancel();
    }

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 初始化view
     */
    public abstract void initView();

    /**
     * 初始化Presenter
     */
    public abstract void initPresenter();


    /**
     * 关闭键盘
     */
    public void closeKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                    0);
        }
    }

    @Override
    public void showToast(String msg) {
        if (!isDeath()) {
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void cancelProgressDialog() {
        if (isDeath()) {
            return;
        }

    }


    @Override
    public void showProgressDialog(String msg) {
        if (isDeath()) {
            return;
        }

    }

    /**
     * 判断页面是否死亡
     *
     * @return
     */
    public boolean isDeath() {
        if (this == null && this.isFinishing()) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (this.isDestroyed()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 设置状态栏颜色
     */
    protected void initSystemBarTint() {
        Window window = getWindow();
        if (true) {
            // 设置状态栏全透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
            return;
        }
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0以上使用原生方法
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4-5.0使用三方工具类，有些4.4的手机有问题，这里为演示方便，不使用沉浸式
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(Color.TRANSPARENT);

        }
    }

    //申请权限
    public void requestPermission(String[]... permission) {
        AndPermission.with(this)
                .runtime()
                .permission(permission)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {

                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {

                    }
                })
                .start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isRegisteredEventBus()) {
            EventBusUtils.unregister(this);
        }
        unregisterReceiver(timeChangeReceiver);
    }
}
